const handler = require('sv-handle-res')
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  // 职业列表
  async professionList() {
    // 联表st-exam-libs查询
    const dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云对象的clientInfo
      clientInfo: this.getClientInfo()
    })
    
    const tempLibsDB = dbJQL.collection('st-exam-libs').field('lib_id,lib_name,lib_title,icon,sell_num').getTemp()
    const professionRes = await dbJQL.collection('st-profession-list', tempLibsDB).orderBy('sort', 'asc').get()

    return handler.result({
      data: professionRes.data,
    })
  },
  // 更新职业
  async professionUpdate() {
    const {
      _id,
      profession_id,
      profession_name
    } = this.params

    if (!profession_id || !profession_name) {
      throw handler.result({
        code: 40001
      })
    }

    delete this.params._id // 移除_id字段，_id不参与更新
    const professionRes = await db.collection('st-profession-list').doc(_id).update(this.params)

    return handler.result({
      data: professionRes,
    })
  },
  // 添加职业
  async professionAdd() {
    const {
      profession_id,
      profession_name
    } = this.params

    if (!profession_id || !profession_name) {
      throw handler.result({
        code: 40001
      })
    }

    const professionRes = await db.collection('st-profession-list').add(this.params)

    return handler.result({
      data: professionRes,
    })
  },
  // 删除职业
  async professionDelete() {
    const {
      profession_id
    } = this.params

    if (!profession_id) {
      throw handler.result({
        code: 40001
      })
    }

    const professionRes = await db.collection('st-profession-list').where({
      "profession_id": dbCmd.eq(profession_id)
    }).remove()

    return handler.result({
      data: professionRes,
    })
  },
}